package redis.lock;

import org.redisson.Redisson;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.redisson.config.Config;

import java.util.concurrent.TimeUnit;

/**
 * create by LiangYM @Date 2020/7/23 13:54
 **/
public class RedisLockDemo {

    private static final String lockKey = "lock";

    public static void main(String[] args) {
        Config config = new Config();
        config.useSingleServer().setAddress("redis://127.0.0.1:6379").setDatabase(0);
        RedissonClient redissonClient = Redisson.create(config);
        RLock lock = redissonClient.getLock(lockKey);
        try {
            //Redisson有解决这个问题, 当发现超时后, 业务还没执行完, 会有监控线程去重新设置这个时间
            lock.lock(30, TimeUnit.SECONDS);
            System.out.println("获取锁成功，实现业务逻辑");
            //TODO
            int i=100;
            while (i>0){
                i--;
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }


    }

}
